//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: '欢迎使用教学管理小程序',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    phone: '',
    password: ''
  },
  //事件处理函数
  bindViewTap: function() {
    /*wx.navigateTo({
      url: '../logs/logs'
    })*/
  },
  onLoad: function () {
    //如果用户信息存在
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  bindUser: function(e){
    /*
    //给对象添加属性值
    var phone = 'userInfo.phone';
    var that = this;
    that.setData({
      [phone]: '13991613401'
    });
    console.log(that.data.userInfo);*/
    var that = this;
    //1、检查手机号和密码是否为空
    if(!(that.data.phone.length && that.data.password)){
      wx.showModal({
        title: '提示',
        content: '手机号和密码不能为空!',
        showCancel: false,
        success: function (res) {}
      })
      return;
    }
    //2、获取登录code
    wx.login({
      success: function(res) {
        console.log(res)
        var _url = `${app.globalData.serverUri}/usr/login`;
        var _data = {
          code: res.code,
          phone: that.data.phone,
          password: that.data.password
        }
        //第三方登录
        wx.request({
          url: _url,
          data: _data,
          method: 'GET',
          dataType: 'json',
          responseType: 'text',
          success: function(res) {
            console.log(res);
          },
          fail: function(res) {},
          complete: function(res) {},
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  bindPhone: function(event){
    this.setData({phone: event.detail.value})
  },
  bindPassword: function (event) {
    this.setData({ password: event.detail.value })
  }
})
